<template>
  <!-- hidden PageHeaderWrapper title demo -->
  <page-header-wrapper :title="false" content="表单页用于向用户收集或验证信息，基础表单常见于数据项较少的表单场景。">
    <a-card  :bordered="false">
      <a-button type="primary" icon="plus" style="margin-right: 0px;" @click="groupModal = true">分类</a-button>
      <a-select v-model="groupId" style="width: 200px">
        <a-select-option v-for="(item, index) in groupList" :key="index" :value="item.id">{{item.groupName}}</a-select-option>
      </a-select>
      <a-modal v-model="groupModal" title="添加分类" ok-text="确认" cancel-text="取消" @ok="saveGroup">
        <a-input placeholder="分类名称" v-model="addGroupName"/>
      </a-modal>
    </a-card>
    <a-card :body-style="{padding: '24px 32px'}" :bordered="false">
      <a-row>
        <a-col :span="6">
          <a-form @submit="handleSubmit" :form="form">
            <a-form-item
              label="name"
              :labelCol="{lg: {span: 7}, sm: {span: 7}}"
              :wrapperCol="{lg: {span: 14}, sm: {span: 17} }">
              <a-input
                v-decorator="[
                  'name',
                  {rules: [{ required: true, message: 'name' }]}
                ]"
                name="name"
                placeholder="name"/>
            </a-form-item>
            <a-form-item
              label="description"
              :labelCol="{lg: {span: 7}, sm: {span: 7}}"
              :wrapperCol="{lg: {span: 14}, sm: {span: 17} }">
              <a-textarea
                rows="2"
                placeholder="Description"
                v-decorator="[
                  'description',
                  {rules: [{ required: true, message: 'description' }]}
                ]" />
            </a-form-item>
            <a-form-item
              label="Pipeline workers"
              :labelCol="{lg: {span: 7}, sm: {span: 7}}"
              :wrapperCol="{lg: {span: 14}, sm: {span: 17} }">
              <a-input-number style="width: 265px"
                              placeholder="Pipeline workers"
                              v-decorator="[
              'workers',
              {initialValue: 1, rules: [{ required: true, message: 'Pipeline workers' }]}
              ]" />
            </a-form-item>
            <a-form-item
              label="Pipeline batch size"
              :labelCol="{lg: {span: 7}, sm: {span: 7}}"
              :wrapperCol="{lg: {span: 10}, sm: {span: 17} }"
              :required="false"
            >
              <a-input-number :min="0" :max="100"
                              placeholder="Pipeline batch size" style="width: 265px"
                              v-decorator="[
              'batchSize',
              {initialValue: 125, rules: [{ required: true, message: 'Pipeline batch size ' }]}
              ]" />
            </a-form-item>
            <a-form-item
              label="Pipeline batch delay"
              :labelCol="{lg: {span: 7}, sm: {span: 7}}"
              :wrapperCol="{lg: {span: 10}, sm: {span: 17} }"
              :required="false"
            >
              <a-input-number style="width: 265px"
                              placeholder="Pipeline batch delay"
                              v-decorator="[
              'batchDelay',
              {initialValue: 50, rules: [{ required: true, message: 'Pipeline batch delay' }]}
              ]" />
            </a-form-item>
            <a-form-item
              label="Queue type"
              :labelCol="{lg: {span: 7}, sm: {span: 7}}"
              :wrapperCol="{lg: {span: 10}, sm: {span: 17} }"
              :required="false"
            >
              <a-select style="width: 265px" v-decorator="[
              'queueType',
              {initialValue:'memory', rules: [{ required: true, message: 'Queue type ' }]}
              ]">
                <a-select-option value="memory">
                  memory
                </a-select-option>
                <a-select-option value="persisted">
                  persisted
                </a-select-option>
              </a-select>
            </a-form-item>
            <a-form-item
              label="Queue max bytes"
              :labelCol="{lg: {span: 7}, sm: {span: 7}}"
              :wrapperCol="{lg: {span: 10}, sm: {span: 17} }"
              :required="false"
            >
              <a-input-number style="width: 265px"
                              placeholder="Queue max bytes(MB)"
                              v-decorator="[
              'queueMaxBytes',
              {initialValue: 1024, rules: [{ required: true, message: 'Queue max bytes' }]}
              ]" />
            </a-form-item>
            <a-form-item
              label="Queue checkpoint"
              :labelCol="{lg: {span: 7}, sm: {span: 7}}"
              :wrapperCol="{lg: {span: 10}, sm: {span: 17} }"
              :required="false"
            >
              <a-input-number style="width: 265px"
                              placeholder="Queue checkpoint writes"
                              v-decorator="[
              'queueCheckpointWrites',
              {initialValue: 1024, rules: [{ required: true, message: 'Queue checkpoint writes' }]}
              ]" />
            </a-form-item>
            <a-form-item
              label="run host"
              :labelCol="{lg: {span: 7}, sm: {span: 7}}"
              :wrapperCol="{lg: {span: 10}, sm: {span: 17} }"
              :required="false"
            >
              <a-select style="width: 265px" v-decorator="[
              'expectRunHost',
              {rules: [{ required: false, message: 'run host' }]}
              ]">
                <a-select-option :value="item.tag" v-for="item in hostList">
                  {{item.tag}}
                </a-select-option>
              </a-select>
            </a-form-item>
            <a-form-item
              :wrapperCol="{ span: 24 }"
              style="text-align: center"
            >
              <a-button @click="$router.go(-1)"> <a-icon type="left" />返回 </a-button>
              <a-button style="margin-left: 8px" type="primary" v-if="showSave" @click="handleSubmit(0)">暂存</a-button>
              <a-button style="margin-left: 8px" type="primary" @click="handleSubmit(1)">发布</a-button>
            </a-form-item>
          </a-form>
        </a-col>
        <a-col :span="18">
          <div class="codeDiv">
            <codemirror v-model="codes" :options="options" style="min-height: 500px"></codemirror>
            <div class="versionDiv">
              <a-button style="margin-left: 8px" type="primary" v-text="'version: ' + runCodeVersion"></a-button>
            </div>
          </div>
        </a-col>
      </a-row>
    </a-card>
  </page-header-wrapper>

</template>

<script>
  import { savePipeline, getPipeline } from '@/api/logstash_pipeline'
  import { getGroupList, saveGroup} from '@/api/logstash_group'
  import { getOnlineHostsByProject } from '@/api/agent'


  import {codemirror} from 'vue-codemirror'
  import 'codemirror/lib/codemirror.css'
  // 引入主题,配置后生效
  import 'codemirror/theme/idea.css'
  //引入语言,配置后生效
  import 'codemirror/mode/puppet/puppet.js'


  var beautify = require('js-beautify').js
  export default {
    name: 'BaseForm',
    components: {
      codemirror
    },
    data () {
      return {
        code: 'input {    stdin {}}output {    stdout {    codec => rubydebug  }}',
        form: this.$form.createForm(this),
        //需编辑和显示的内容
        codes: '',
        runCodeVersion: '1.0',
        // 默认配置
        options: {
          tabSize: 2, // 缩进格式
          theme: 'idea', // 指定主题，对应主题库 JS 需要提前引入
          lineNumbers: true, // 是否显示行号
          //指定语言类型,如果需要编辑和显示其他语言,需要import语言js然后修改此配置
          mode: 'puppet',
          line: true,
          styleActiveLine: true, // 高亮选中行
          hintOptions: {
            completeSingle: true // 当匹配只有一项的时候是否自动补全
          }
        },
        groupId: null,
        groupList: [],
        addGroupName: "",
        groupModal: false,
        showSave: true,
        hostList: []
      }
    },
    methods: {
      loadGroups () {
        getGroupList({projectId: this.projectId}).then(res => {
          if(res.code == 200){
            this.groupList = res.data
            if(this.groupList.length > 0){
              this.groupId = this.groupList[0].id
            }
          }
        })
      },
      saveGroup () {
        const me = this
        this.groupModal = false
        if(this.$store.state.project.projectId){
          saveGroup({
            projectId: this.$store.state.project.projectId,
            groupName: this.addGroupName
          }).then(res => {
            this.loadGroups()
            for (let i = 0; i < this.groupList.length; i++) {
              if(this.addGroupName == this.groupList[i].groupName){
                this.groupId = this.groupList[i].id
                this.addGroupName = ""
                break
              }
            }
          })
        }else{
          this.$warning({
            title: '提示',
            content: '请建立项目',
            onOk: function () {
              me.$router.push({ path: '/data-control/project' })
            }
          });
        }
      },
      handleSubmit (status) {
        const me = this
        this.form.validateFields((err, values) => {
          if (!err) {
            if(!this.groupId){
              this.$warning({title: '提示',content: '请选择分类'});
            }
            if(this.$route.query.id){
              values.id = this.$route.query.id
            }
            values.status = status;
            values.runCodeVersion = me.runCodeVersion
            values.projectId = this.$store.state.project.projectId
            values.groupId = this.groupId
            savePipeline({
              pipeline: values,
              codes: me.codes
            }).then(res => {
              if(res.code == 200){
                me.$router.push({ path: '/workplace' })
              }else if(res.code == 531){
                this.$message.error('停止logstash失败，导致无法部署。请检查原因。')
              }else if(res.code == 530){
                this.$message.error('启动logstash失败，请检查原因。')
              }
            })
          }
        })
      },
      getPipeline (id) {
        getPipeline(id).then(res => {
          if(res.code == 200){
            if(res.data){
              let data = res.data
              this.runCodeVersion = (parseFloat(data.runCodeVersion) + 0.1).toFixed(1)
              this.codes = res.pipelineCodes == null ? "" : res.pipelineCodes
              this.showSave = data.status == 0
              this.form.setFieldsValue(data)
            }
          }
        })
      },
      loadHosts () {
        const projectId = this.$store.state.project.projectId
        console.log(projectId)
        getOnlineHostsByProject(projectId).then(res => {
          if (res.code === 200) {
            this.hostList = res.data
          }
        })
      }
    },
    created () {
      this.codes = beautify(this.code)
      this.loadGroups()
      if(this.$route.query.id){
        this.getPipeline(this.$route.query.id)
      }
      this.loadHosts()
    }
  }
</script>
<style>
  .codeDiv {
    border: solid 2px #f0f2f5;
  }
  .CodeMirror {
    overscroll-y: scroll !important;
    height: 700px !important;
  }
  .versionDiv {
    position: absolute;
    top: 0px;
    right: 0px;
    z-index: 99999999;
  }
</style>